package com.xr.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.sunnyday.constant.MessageConstant;
import com.xr.sunnyday.constant.RedisMessageConstant;
import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.pojo.Member;
import com.xr.sunnyday.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.Map;

/**
 * 处理用户登录请求
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @PostMapping("/check")
    public Result checkMember(@RequestBody Map<String,String> loginInfo, HttpServletResponse res){
        //1 .校验登录验证码
        //1.从reis连接池中获取连接
        Jedis jedis = jedisPool.getResource();
        //1.1.拿到用户传过来的手机号
        String telephone = loginInfo.get("telephone");
        //1.2.组拼key
        String key = RedisMessageConstant.SENDTYPE_LOGIN+"_"+telephone;
        //1.3根据key获取
        String codeInRedis = jedis.get(key);
        //1.4判断
        if (StringUtils.isEmpty(codeInRedis)){
            //1.5 null
            return new Result(false,"验证码失效，请重新发送!");
        }
        //2.有值，取出前端页面传过来的验证码
        String validateCode = loginInfo.get("validateCode");
        if (!codeInRedis.equals(validateCode)){
            //2.1如果不一致
            return new Result(false,"验证码错误！");
        }
        //2.2 匹配一致，代表这次请求已经完成，删除redis的key
        //jedis.del(key); //学习阶段，不建议删除
        jedis.close();
        //3.通过验证，判断是不是会员
         Member member = memberService.findByTelephone(telephone);
         if (null==member){
             //3.1没有查到这个会员，帮其注册
             member = new Member();
             //只能填这三项，剩下的给用户自己完善
             member.setRegTime(new Date());
             member.setPhoneNumber(telephone);
             member.setRemark("手机快速注册");
             //3.2添加这个新的member
             memberService.add(member);
         }
        //4.添加成功，把用户信息存Cookie
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setMaxAge(30*24*60*60);//保存一个月
        cookie.setPath("/");//只要访问这个path就会发送Cookie
        res.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }


}
